import json
from rest_framework.views import APIView, Response
from django.http import JsonResponse, HttpResponse
from core.tools.models import ShortMsg, Province, City, QrCodeGroupChat
from captcha.views import CaptchaStore, captcha_image
from rest_framework import status
import base64


class ImageView(APIView):
    def get(self, request):
        hashkey = CaptchaStore.generate_key()
        try:
            # 获取图片id
            id_ = CaptchaStore.objects.filter(hashkey=hashkey).first().id
            imgage = captcha_image(request, hashkey, scale=1)
            # 将图片转换为base64
            image_base = base64.b64encode(imgage.content)
            json_data = {"id": id_, "image_base": "data:image/;base64," + image_base.decode('utf-8')}
            return Response(json_data)
        except Exception as e:
            print(e)
            json_data = {"error": "获取验证码错误，重新获取"}
            return Response(json_data, status=status.HTTP_400_BAD_REQUEST)


def short_msg(request):
    tel = request.POST.get('tel')
    # tel = "18612386233"
    if not tel:
        context = {"msg": "请输入手机号", "status": "error"}
        return JsonResponse(context)
    s_info, created = ShortMsg.objects.get_or_create(tel=tel)
    if not s_info.num or s_info.num < 10:
        if s_info.get_update_time():
            if s_info.send_code():
                context = {"msg": "短信已发送至手机，请注意查收", "status": "ok"}
            else:
                context = {"msg": "短信发送失败请稍后重试", "status": "error"}
        else:
            context = {"msg": "请勿重复操作", "status": "error"}
    else:
        context = {"msg": "短信发送数量已达上限，请稍后重试", "status": "error"}
    return JsonResponse(context)


def get_city(request):
    p_list = Province.objects.all()
    province_list = []
    city_list = []
    area_list = []
    for i in p_list:
        city_json_list = []
        for city in i.province_city.all():
            area_json_list = []
            for area in city.city_district.all():
                area_json_list.append({"label": area.name, "value": str(area.id)})
            area_list.append(area_json_list)
            city_json_list.append({"label": city.name, "value": str(city.id)})
        city_list.append(city_json_list)
        province_list.append({"label": i.name, "value": str(i.id)})
    content = {"province_list": province_list, "city_list": city_list, "area_list": area_list}
    return JsonResponse(content)


def get_area(request):
    c_list = City.objects.all()
    json_list = []
    for i in c_list:
        base_list = []
        for area in i.city_district.all():
            d = {
                "label": area.name,
                "value": str(area.id)
            }
            base_list.append(d)
        json_list.append(base_list)
    return JsonResponse(json_list, safe=False)


# 群聊二维码
def get_group_chat_qr_code(request):
    qr_code_instance = QrCodeGroupChat.objects.first()
    img_type = qr_code_instance.img.name.split(".")[-1]
    content_type = "image/%s" % img_type
    with open(qr_code_instance.img.path, 'rb') as f:
        image_data = f.read()
    return HttpResponse(image_data, content_type=content_type)
